package cc.linker.steplink.crm.merchant.task;

import cc.linker.steplink.crm.commons.enums.IntegralEnums;
import cc.linker.steplink.crm.commons.coupon.CouponCustomerInfo;
import cc.linker.steplink.crm.commons.lock.RedisLock;
import cc.linker.steplink.crm.merchant.dao.acs.MerchantOrderMapper;
import cc.linker.steplink.crm.merchanth5.dao.MallBoomDao;
import cc.linker.steplink.crm.merchanth5.dao.integral.IntegralH5Dao;
import cc.linker.steplink.crm.merchanth5.pojo.OrderScore;
import cc.linker.steplink.crm.merchanth5.dao.MallDao;
import cc.linker.steplink.crm.merchanth5.dao.acs.PurchaseProcessDao;
import cc.linker.steplink.crm.merchanth5.service.CustomerIntegralService;
import cc.linker.steplink.crm.merchanth5.service.MallService;
import cc.linker.steplink.crm.merchanth5.service.acs.PurchaseProcessService;
import cc.linker.steplink.crm.merchanth5.service.coupon.CouponH5Service;
import cc.linker.steplink.crm.merchanth5.service.impl.PurchaseProcessNewServiceImpl;
import cc.linker.steplink.crm.merchanth5.service.tl.LedgerProcessService;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 中金支付自动确认订单
 *
 * @author whf
 */
@Component
public class AcsAutoConfirmOrderTask {

    @Autowired
    private MerchantOrderMapper merchantOrderMapper;
    @Autowired
    private MallService mallService;
    @Autowired
    private PurchaseProcessService purchaseProcessService;
    @Autowired
    private PurchaseProcessDao purchaseProcessDao;
    @Autowired
    private MallDao mallDao;
    @Autowired
    private MallBoomDao mallBoomDao;
    @Autowired
    private LedgerProcessService ledgerProcessService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private IntegralH5Dao integralH5Dao;
    @Autowired
    private CustomerIntegralService customerIntegralService;
    @Autowired
    private CouponH5Service couponH5Service;

    @RedisLock("AcsAutoConfirmOrderTask")
    @Scheduled(cron = "14 */1 * * * ?")
    //@Scheduled(cron = "1 * * * * ?")
    public void autoConfirmOrderTask() {
        // 获取待确认订单sn,orderSn,customerId,orgId
        List<Map<String, Object>> orderInfoList = merchantOrderMapper.getOrderSnWhereAutoConfirm();
        for (Map<String, Object> map : orderInfoList) {
            map.put("objectId", map.get("orderSn"));
            mallService.addToDealData(map, 5);
        }
        // 自动确认
        List<Map<String, Object>> orderList = merchantOrderMapper.listOrderWhereNeedConfirm();
        List<String> orderSnList = orderList.stream()
                .map(x -> (String) x.get("orderSn"))
                .distinct()
                .collect(Collectors.toList());
        if (orderList.size() > 0) {
            merchantOrderMapper.updateStatusWhereAutoConfirm(orderSnList);
        }
        for (Map<String, Object> map : orderList) {
            String orgId = (String) map.get("orgId");
            String orderSn = (String) map.get("orderSn");
            boolean b = purchaseProcessService.judgeOrderIfInRefundByOrderSn(orderSn);
            if (!b) {
                // 未退款的才更新end_time
                String unfreezeTime = purchaseProcessService.getUnfreezeTimeByOrgId(orgId);
                purchaseProcessService.updateProtectStatusWhereAutoConfirm(orderSn, unfreezeTime);
            }
        }

        // 自动关闭超过一小时未付款的订单
        List<String> orderIds = merchantOrderMapper.listOrderWhereExpired();
        if (orderIds.isEmpty()) {
            return;
        }
        merchantOrderMapper.closeOrderWhereExpired(orderIds);
        // 恢复积分
        for(String orderId:orderIds){
            Map<String,Object> params = new HashMap<>(1);
            params.put("orderId",orderId);

            Map orderInfo = mallBoomDao.getOrderInfoById(Long.valueOf(params.get("orderId").toString()), 1);
            Long score = Long.valueOf(orderInfo.get("score").toString());
            if(score>0){
                params.put("score",score);
                // 恢复积分
                params.put("customerId",orderInfo.get("customerId"));
                mallDao.recoveryScoreById(params);
                //记录金币变动记录
                Map<String,Object> scoreLog = new HashMap<>();
                scoreLog.put("customerId",orderInfo.get("customerId"));
                scoreLog.put("score",score);
                scoreLog.put("type",2);
                scoreLog.put("orderSn",orderInfo.get("orderSn"));
                purchaseProcessDao.addScoreLog(scoreLog);
                try {
                    //根据id查出orderSn，paySn，payMode
                    OrderScore orderScore = mallDao.getOrderScore(orderId);
                    if(orderScore!=null){
                        String balanceSplitItemsString = stringRedisTemplate.opsForValue().get(PurchaseProcessNewServiceImpl.CANCEL_SCORE_ORDER+orderScore.getOrderSn());
                        List<Map> balanceSplitItems = JSON.parseArray(balanceSplitItemsString, Map.class);
                        Integer balanceAmount = 0;
                        if(balanceSplitItems!=null && balanceSplitItems.size()>0){
                            for (Map<String, Object> balanceSplitItemA : balanceSplitItems){
                                Integer amount = 0;
                                if(!StringUtils.isEmpty(balanceSplitItemA.get("amount"))){
                                    amount = (Integer) balanceSplitItemA.get("amount");
                                }
                                balanceAmount = balanceAmount+ amount;
                            }
                        }
                        List<Map<String, Object>> cashSplitItems = new ArrayList<>();
                        String cashSplitItemsString = JSON.toJSONString(cashSplitItems);
                        if(balanceAmount>0){
                            ledgerProcessService.refund(orderScore.getOrderSn(), balanceAmount.toString(), balanceSplitItemsString, "0", cashSplitItemsString,orderScore.getPaySn(),orderScore.getPayMode());
                        }

                    }
                    String consumptionId =(String) orderInfo.get("consumptionId");
                    String couponId = (String) orderInfo.get("couponId");
                    if(!StringUtils.isEmpty(consumptionId) && !StringUtils.isEmpty(couponId)){
                        String customerId = "";
                        if(!StringUtils.isEmpty(orderInfo.get("customerId"))){
                            customerId = orderInfo.get("customerId").toString();
                        }
                        String orgId = "";
                        if(!StringUtils.isEmpty(orderInfo.get("orgId"))){
                            orgId = orderInfo.get("orgId").toString();
                        }
                        CouponCustomerInfo couponCustomerInfo = CouponCustomerInfo
                                .builder()
                                .customerId(customerId)
                                .customerName("")
                                .customerPhone("")
                                .cover("")
                                .orgId(orgId)
                                .build();
//                        CouponCustomerInfo couponCustomerInfo = (CouponCustomerInfo) params.get("couponCustomerInfo");
                        //使用优惠券回滚
                        couponH5Service.useConsumption(consumptionId,null,orderInfo.get("orderSn").toString(),null,null,1,couponCustomerInfo);
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        // 订单关闭后恢复库存
        List<Map<String, Object>> orders = merchantOrderMapper.listOrderByOrderId(orderIds);
        for (Map<String, Object> order : orders) {
            Long goodsId = Long.valueOf(order.get("goodsId").toString());
            Long mallsGoodsId =  purchaseProcessDao.getMallsGoodsIdByGoodsId(goodsId);
            String skuId = "";
            if (order.get("skuId") != null && !"".equals(order.get("skuId"))) {
                skuId = order.get("skuId").toString();
            }
            Integer goodsNum = 0;
            if (order.get("goodsNum") != null && !"".equals(order.get("goodsNum"))) {
                goodsNum = Integer.valueOf(order.get("goodsNum").toString());
            }
            mallService.rollBackMallsGoodsCount(goodsId,skuId,goodsNum,mallsGoodsId);
        }
    }


    @RedisLock("autoIntegralConfirmOrderTask")
    @Scheduled(cron = "45 */1 * * * ?")
    public void autoIntegralConfirmOrderTask() {
        // 获取待确认订单sn,orderSn,customerId,orgId
        List<Map<String, Object>> orderInfoList = integralH5Dao.getOrderSnWhereAutoConfirm();
        // 自动确认
        List<Map<String, Object>> orderList = integralH5Dao.listOrderWhereNeedConfirm();
        List<String> orderSnList = orderList.stream()
                .map(x -> (String) x.get("orderSn"))
                .distinct()
                .collect(Collectors.toList());
        if (orderList.size() > 0) {
            integralH5Dao.updateStatusWhereAutoConfirm(orderSnList);
        }
        for (Map<String, Object> map : orderList) {
            String orgId = (String) map.get("orgId");
            String orderSn = (String) map.get("orderSn");
//            boolean b = purchaseProcessService.judgeOrderIfInRefundByOrderSn(orderSn);
//            if (!b) {
//                // 未退款的才更新end_time
//                String unfreezeTime = purchaseProcessService.getUnfreezeTimeByOrgId(orgId);
//                purchaseProcessService.updateProtectStatusWhereAutoConfirm(orderSn, unfreezeTime);
//            }
            String unfreezeTime = purchaseProcessService.getUnfreezeTimeByOrgId(orgId);
            purchaseProcessService.updateProtectStatusWhereAutoConfirm(orderSn, unfreezeTime);

        }

        // 自动关闭超过一小时未付款的订单
        List<String> orderIds = integralH5Dao.listOrderWhereExpired();
        if (orderIds.isEmpty()) {
            return;
        }
        integralH5Dao.closeOrderWhereExpired(orderIds);
        // 恢复积分
        for(String orderId:orderIds){
            Map<String,Object> params = new HashMap<>(1);
            params.put("orderId",orderId);
            Map orderInfo = integralH5Dao.getOrderInfoById(Long.valueOf(params.get("orderId").toString()));
            String msg = "取消兑换商品";
            Long score = 0L;
            if(!StringUtils.isEmpty(orderInfo.get("integral"))){
                score = Long.valueOf(orderInfo.get("integral").toString());
            }
            String customerId="";
            if(!StringUtils.isEmpty(orderInfo.get("customerId"))){
                customerId = orderInfo.get("customerId").toString();
            }
            String orgId="";
            if(!StringUtils.isEmpty(orderInfo.get("orgId"))){
                orgId = orderInfo.get("orgId").toString();
            }
            String orderSn="";
            if(!StringUtils.isEmpty(orderInfo.get("orderSn"))){
                orderSn = orderInfo.get("orderSn").toString();
            }
            this.customerIntegralService.addIntegralCustomerLog(customerId,msg, IntegralEnums.customerScore.toString(),score.toString(),IntegralEnums.other.toString(),orgId);
            //增加日志
            Map<String, Object> log = new HashMap<String, Object>();
            log.put("logId", UUID.randomUUID().toString());
            log.put("customerId", customerId);
            log.put("scoreValue",score);
            log.put("scoreType", 6);
            log.put("actionRemark", "取消兑换，订单号"+orderSn+",增加"+score+"积分");
            integralH5Dao.addIntegralLog(log);
        }

        // 订单关闭后恢复库存
        List<Map<String, Object>> orders = integralH5Dao.listOrderByOrderId(orderIds);
        for (Map<String, Object> order : orders) {
            Long goodsId = Long.valueOf(order.get("goodsId").toString());
            String skuId = "";
            if (order.get("skuId") != null && !"".equals(order.get("skuId"))) {
                skuId = order.get("skuId").toString();
            }
            Integer goodsNum = 0;
            if (order.get("goodsNum") != null && !"".equals(order.get("goodsNum"))) {
                goodsNum = Integer.valueOf(order.get("goodsNum").toString());
            }        Map<String, Object> mapM = new HashMap<>();
            mapM.put("goodsNum", goodsNum);
            Long goodsIdGoods = goodsId;
            mapM.put("goodsId", goodsIdGoods);
            integralH5Dao.addMallGoodsCount(mapM);
            if (!StringUtils.isEmpty(skuId)) {
                Map<String, Object> map = new HashMap<>();
                map.put("skuId", skuId);
                map.put("goodsNum", goodsNum);
                integralH5Dao.addMallGoodsSkuCount(map);
            }

        }
    }
}
